package com.hxx.day2.action;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;

public class TestSort {
    @Test
    public void test1(){//冒泡
        int[] data = {3,1,6,2,5};
        for (int i=data.length-1; i>0; i--) {
            for (int j=0; j<i; j++) {
                if (data[j] > data[j+1]) {
                    int temp = data[j];
                    data[j]	= data[j+1];
                    data[j+1] = temp;
                }
            }
        }
        for (int i=0; i<data.length; i++) {
            System.out.println(data[i]);
        }
    }

    //选择排序
    @Test
    public void test2(){
        int[] data = {3,1,6,2,5};
        for (int i=0; i<data.length; i++) {
            int min = i;
            for (int j=i+1; j<data.length; j++) {
                if (data[j] < data[min]) {
                    min = j;
                }
            }
            //进行位置的交换
            if (min != i) {
                int temp = data[i];
                data[i] = data[min];
                data[min] = temp;
            }

        }
        for (int i=0; i<data.length; i++) {
            System.out.println(data[i]);
        }
    }

    //折半查找
    @Test
    public void test3(){
        int[] data = {11,12,13,14,15,16,17,18,19,20};
        int index = binarySearch(data, 18);
        System.out.println(index);
    }
    //采用折半法查询，必须建立在排序的基础上
    private static int binarySearch(int[] data, int value) {
        //开始下标
        int beginPos = 0;
        //结束下标
        int endPos = data.length - 1;
        //查找
        while (beginPos <=endPos) {
            int midPos = (beginPos + endPos)/2;
            if (value == data[midPos]) {
                return midPos;
            }else if (value > data[midPos]) {
                beginPos = midPos + 1;
            }else if (value < data[midPos]) {
                endPos = midPos - 1;
            }
        }
        return -1;
    }

    @Test
    public void test4(){
        int[] arr = {3,1,6,2,5};
        //排序
        Arrays.sort(arr);
        Arrays.stream(arr).forEach(System.out::println);
        System.out.println("------------------------");
        //两分法查找
        int index = Arrays.binarySearch(arr, 5);
        System.out.println(index);
    }

}
